<?php
include "include/config.inc.php";

if(!isset($_SESSION['s_activId']))
{
  header('location:index.php');
}
$today = date("d-m-Y");
$msg   = "";
if(isset($_POST['amountReceiveTxt']) && $_POST['amountReceiveTxt'] != "")
{
	$amount      = $_POST['amountReceiveTxt'] ;
	$loanNo      = (isset($_POST['loanNoTxt'])) ? $_POST['loanNoTxt'] : "";
	$note        = (isset($_POST['amountReceiveNoteTxt'])) ? $_POST['amountReceiveNoteTxt'] : "";
	$currentDate = $_POST['curDateYear']."-".$_POST['curDateMonth']."-".$_POST['curDateDay'];
  $checkLoan = "SELECT loanId,pendingAmount
	                FROM loan 
	               WHERE loanId = ".$loanNo."
	                 AND isSold = 'N'
	                 AND isDeleted = 'N'";
	$checkLoanRes = mysql_query($checkLoan);
	if($checkLoanRes)
	{
	  $checkLoanRow = mysql_fetch_array($checkLoanRes);
	  $checkLoanNumRow = mysql_num_rows($checkLoanRes);
	  if($checkLoanNumRow > 0)
	  {
      $insertRojmel = "INSERT INTO rojmel(date,`amount`,`debitCredit`,`accountId`,`loanId`,`note`)
                        VALUE ('".$currentDate."',".$amount.",'Cr',5,".$loanNo.",'".$note."')";
      $insertRojmelRes = mysql_query($insertRojmel);
      if($checkLoanRow['pendingAmount'] <= $amount)
      {
        $updateLoan = "UPDATE loan 
                          SET pendingAmount = 0,
                              isDeleted = 'Y' 
                        WHERE loanId =".$loanNo;
        $updateLoanRes = mysql_query($updateLoan);
      }
      else
      {
      	$updateAmount  = $checkLoanRow['pendingAmount'] - $amount;
        $updateLoan    = "UPDATE loan
                             SET pendingAmount =".$updateAmount."
                           WHERE loanId =".$loanNo;
        $updateLoanRes = mysql_query($updateLoan);
        $deleteInterest = "DELETE FROM interestreceived 
                            WHERE loanId =".$loanNo."
                              AND dateOfInstallment >".$currentDate;
      }
    }
    else
    {
      $msg = "Lone No Not Exist ";
    }
  }
  else
  {
    $msg = "Enter Proper Loan No";
  }
}
include("bottom.php");
$smarty->assign("today",$today);
$smarty->assign("msg",$msg);
$smarty->display('amountReceive.tpl');  
?>